/*
 * Copyright 2019-2025 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * https://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.iiifi.kite.boot.web.servlet.config;

import java.nio.charset.StandardCharsets;
import java.util.List;

import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.iiifi.kite.boot.properties.KiteJacksonProperties;
import com.iiifi.kite.core.jackson.MappingApiJackson2HttpMessageConverter;

import lombok.AllArgsConstructor;

/**
 * 消息转换器
 *
 * @author kite@iiifi.com 花朝
 */
@Configuration
@AllArgsConstructor
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class KiteMessageConfiguration implements WebMvcConfigurer {

    private final KiteJacksonProperties properties;
    private final ObjectMapper objectMapper;

    /**
     * 消息转换，内置断点续传，下载和字符串
     *
     * @param converters 转换器
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.removeIf(
                x -> x instanceof StringHttpMessageConverter || x instanceof AbstractJackson2HttpMessageConverter);
        converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        // 如果需要将 null 转为 空
        if (properties.getNullToEmpty()) {
            converters.add(new MappingApiJackson2HttpMessageConverter(objectMapper));
        } else {
            converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
        }
    }
}
